package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.model.db.Admin;
import com.tanhua.model.vo.AdminVo;
import com.tanhua.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //管理员登录获取token
    public String login(String username, String password, String code, String uuid) {
        //1.判断用户输入的验证码和Redis中的是否一致
        String key = "CODE_" + uuid;
        String value = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(value) || !value.equals(code)) {
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(key);
        //2.根据用户名，查询管理员对象
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username", username);
        Admin admin = adminMapper.selectOne(qw);
        //3.判断对象是否存在，判断数据库中的密码和输入的密码是否一致
        //数据库中的密码是加密之后的。将用户登录时输入的密码进行加密
        password = SecureUtil.md5(password);
        if (admin == null || !admin.getPassword().equals(password)) {
            throw new BusinessException("用户名或者密码错误");
        }
        //4.生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id", admin.getId());
        String token = JwtUtils.getToken(tokenMap);
        //5.返回
        return token;
    }

    //根据token获取管理员信息
    public AdminVo profile() {
        //1.获取当前管理员id
        Long userId = AdminHolder.getUserId();
        //2.调用mapper，根据id查询管理员对象  Admin
        Admin admin = adminMapper.selectById(userId);
        //3.转化vo
        return AdminVo.init(admin);
    }
}
